package com.example.baiduapi.Util;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@Configuration
public class PostUtil {

    private static Logger LOG = LoggerFactory.getLogger(PostUtil.class);

    /**
     * @param defURL 请求地址
     * @param param 请求体
     **/
    public static String postRequest(String defURL,String param) throws Exception {
            URL url = new URL(defURL);
            // 打开和URL之间的连接
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setRequestMethod("POST");//请求post方式
            con.setUseCaches(false); // Post请求不能使用缓存
            con.setDoInput(true);// 设置是否从HttpURLConnection输入，默认值为 true
            con.setDoOutput(true);// 设置是否使用HttpURLConnection进行输出，默认值为 false

            //设置header内的参数 connection.setRequestProperty("健, "值");
            con.setRequestProperty("Content-Type", "application/json;charset=utf-8");


            // 建立实际的连接
            con.connect();

            // 得到请求的输出流对象
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(),"UTF-8");
            writer.write(param.toString());
            writer.flush();

            // 获取服务端响应，通过输入流来读取URL的响应
            InputStream is = con.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sbf = new StringBuffer();
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();

            // 关闭连接
            con.disconnect();

            // 打印读到的响应结果
            System.out.println("运行结束："+sbf.toString());
        return sbf.toString();
    }




/*    public static Map postRequest2() throws Exception {
        String res=new ShowApiRequest("https://route.showapi.com/28-1","1519099","e49dca8b960e44298efc5bb024c5d1a5")
                .addTextPara("tNum","")
                .addTextPara("tNumAlias","示例模板1")
                .addTextPara("mobile","16608676369")
                .addTextPara("content","{\"code\":\"123456\"}")
                .addTextPara("big_msg","")
                .post();
        System.out.println(res);
        return JSON.parseObject(res,Map.class);
    }*/

}
